package com.mtao.security;

import com.mtao.dto.JwtUserDto;
import com.mtao.SysRoleService;
import com.mtao.SysUserService;
import com.mtao.exception.BadRequestException;
import com.mtao.entity.SysUser;
import jakarta.annotation.Resource;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * 用户信息处理
 */
@Component
//@RequiredArgsConstructor
//@Service("userDetailsService")
public class SecurityUserDetailsService implements UserDetailsService {

    @Resource
    private SysUserService userService;
    @Resource
    private SysRoleService roleService;

    /**
     * 通过用户名查询用户信息
     *
     * @param username 用户名
     * @return 用户信息
     * @throws UsernameNotFoundException 用户不存在
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = null;
        try {
            sysUser = userService.findByName(username);
        } catch (BadRequestException e) {
            throw new UsernameNotFoundException("用户名或密码错误!", e);
        }
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户名或密码错误!");
        } else {
            if (!sysUser.getEnabled()) {
                throw new BadRequestException("账号未激活！");
//                    throw new UsernameNotFoundException("账号未激活！");
            }
            return new JwtUserDto(sysUser, sysUser.getId(),roleService.getRolesByUser(sysUser.getId()));
        }
    }
}
